package com.sudu.tool.impl;

import com.sudu.tool.FileUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.UUID;

@Component
public class fileUtilImpl implements FileUtil {
    final String baseUrl = "http://1.116.162.146:8080";
    //获取编译文件夹下的static路径
    final String basePath =  "/home/bilibili/bili" ;


    /**
     * 文件上传
     *
     * @param filePath 路径
     * @param file     文件
     * @return String 文件路径
     */
    @Override
    public String uploadOne(String filePath, MultipartFile file) {
        System.out.println("=======================================" +  basePath);
        File MyFile = new File(basePath + filePath );
        if (!MyFile.exists()) {//文件夹不存在
            MyFile.mkdirs();//创建文件夹
        }
        System.out.println("myfile=================" + MyFile) ;
        //文件输出流
        FileOutputStream fileOutputStream = null;
        //缓冲输出流
        BufferedOutputStream bufferedOutputStream = null;
        //要上传的图片文件
        File imgFile = null;
        //要上传的图片名
        String imgName = null;
        //上传后图片的url
        String imgUrl = null;
        try {
            //获取图片二进制数据
            byte[] bytes = file.getBytes();
            if (filePath == "/cover") {
                imgName = UUID.randomUUID() + ".jpg";
            } else if (filePath == "/video") {
                imgName = UUID.randomUUID() + ".mp4";
            } else if (filePath == "/image") {
                imgName = UUID.randomUUID() + ".jpg";
            }

            imgFile = new File(MyFile, imgName);
            //文件输出流对象
            fileOutputStream = new FileOutputStream(imgFile);
            //缓冲流对象
            bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
            //将图片数据写入文件
            bufferedOutputStream.write(bytes);
            //数据推出管道流
            bufferedOutputStream.flush();
            //关闭输出流
            bufferedOutputStream.close();
            //将图片的url写到类中
            imgUrl = baseUrl + filePath + "/" + imgName;
            return imgUrl;
        } catch (IOException e) {//发生IO异常
            e.printStackTrace();
            return null;
        }

    }



    /**
     * 根据url 根据 url 删除单文件
     *
     * @param fileUrl
     * @return boolean 删除结果
     */
    @Override
    public boolean deleteFile(String fileUrl) {
        String path = getPath(fileUrl);
        File file = null;
        try {
            file = new File(path);
            file.delete();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

    }




    private String getPath(String url) {
        //找到端口号所在下标,并移位至端口号之后
        int i = url.indexOf(":8080") + 5;
        //文件相对路径
        String relativePath = url.substring(i);
        String path = basePath + relativePath;
        return path;

    }
}
